package version

import (
	"errors"
	"log"
	"strconv"
	"strings"
)

// func: GetLastVersion_Three(data []string) string
// aim: 获取最大的版本号, 比如 v2.0.0 > v1.1.1, v可以大小写，可以不写

func GetLastVersion_Three(data []string) (string, error) {
	var res string
	var idx int
	curMaxVersion := make([]int, 3) // 当前组大版本


	for k, v := range data {
		up, err := getThree(v)
		if err != nil {
			return res, err
		}

		if len(curMaxVersion) == 0 {
			curMaxVersion = up
		}

		if len(curMaxVersion) != 3 {
			e := "当前最大版本长度不正确"
			log.Fatalln(e)
			return res, errors.New(e)
		}

		if up[0] > curMaxVersion[0] {
			curMaxVersion = up
			idx = k
			continue
		}
		if up[1] > curMaxVersion[1] {
			curMaxVersion = up
			idx = k
			continue
		}
		if up[2] > curMaxVersion[2] {
			curMaxVersion = up
			idx = k
			continue
		}
	}

	return data[idx], nil
}

// 获取版本的三个数字
func getThree(s string) ([]int, error) {
	res := make([]int, 0)
	s2 := strings.ReplaceAll(strings.ToUpper(s), "V", "")
	for _, v := range strings.Split(s2, ".") {
		atoi, err := strconv.Atoi(v)
		if err != nil {
			return res, err
		}
		res = append(res, atoi)
	}

	return res, nil
}